package com.workflow.service.impl;

import java.util.Date;
import java.util.List;

import com.common.util.AbstractManager;
import com.common.util.DateHelper;
import com.common.util.PagerModel;
import com.workflow.bean.Applydept;
import com.workflow.service.ApplydeptService;

public class ApplydeptServiceImpl extends AbstractManager implements
		ApplydeptService {

	public void addApplydept(Applydept applydept) {
		StringBuilder applyno = new StringBuilder();
		Long count = 0L;
		String hql = "select count(*) from Applydept";
		count = (Long) this.getHibernateTemplate().find(hql).get(0);
		count %= 1000L;
		
		Long num = Long.parseLong(DateHelper.dateToStr(new Date(), "yyyyMMddHms"));
		num *= 1000L;		
		num += count;
		
		applyno.append(applydept.getDepartmentByDeptcode().getDeptcode());
		applyno.append("-BL-");
		applyno.append(num);
		
		applydept.setApplyno(applyno.toString());
		applydept.setStartdate(new Date());
		
		this.getHibernateTemplate().save(applydept);
	}

	@SuppressWarnings("unchecked")
	public List<Applydept> findAllApplydept() {
		String hql = "from Applydept app order by app.departmentByDeptcode.deptcode, app.applyno ";
		return this.getHibernateTemplate().find(hql);
	}

	public Applydept findApplydept(String applyno) {
		return (Applydept) this.getHibernateTemplate().load(Applydept.class, applyno);
	}

	public PagerModel findApplydeptForPager() {
		String hql = "from Applydept app order by app.departmentByDeptcode.deptcode, app.applyno ";
		return searchPaginated(hql);
	}

	public PagerModel findApplydeptForPager(String deptcode) {
		if(deptcode == "") {
			return findApplydeptForPager();
		}
		
		String hql = "from Applydept app where app.departmentByDeptcode.deptcode = ? or " +
				" app.departmentByDepartmentDeptcode.deptcode = ? order by app.applyno "; 
		return searchPaginated(hql,new String[]{deptcode,deptcode});
	}

	public void removeApplydept(String applyno) {
		Applydept applydept = null;
		
		String hql = "from Applydeptdetail appd where appd.applydept.applyno = ?";
		List list = this.getHibernateTemplate().find(hql,applyno);
		
		if(list == null || list.size() == 0) {
			applydept = (Applydept) this.getHibernateTemplate().load(Applydept.class, applyno);
			if(applydept != null) {
				this.getHibernateTemplate().delete(applydept);
			}
		} else {
			throw new RuntimeException("you shall remove the items of Applydeptdetail before with Applydept applyno:"+applyno);
		}

	}

	public void updateApplydept(Applydept applydept) {
		this.getHibernateTemplate().update(applydept);
	}

}
